import axios from 'axios';
import {
    Toast
} from 'vant';
import {
    isApp,
    isAndroid,
    getParamsFromUrl,
    getUaData,
    buildParams,
} from './common'
import { Encrypt, Decrypt, Authorization } from "./aes.min.js";
// import AES from "./aes.js";
//import { Encrypt, Decrypt, Authorization }  from "./aes.js";
/*
 * 因为正式环境签名一分钟就会过期，所以每次请求之前主动重新向app获取签名，如果
 * 有需求是在app内部不用token就可以获取数据的接口，请求的时候把flag设置成true,
 * 这样不用传token也能正常获取数据
 *
 * */
/*"hxs-gin-dev"//*/
const getBaseArg = () => {
    return {
        sess_token: getParamsFromUrl('sess_token') || getUaData('sess_token'),
        utime: getParamsFromUrl('utime') || getUaData('utime'),
        sign: decodeURIComponent(getParamsFromUrl('sign') || getUaData('sign'))
            // sign: "hxs-gin-dev"
    }
};

/*先进先出*/
const funcs = [];

function getUserInfo(flag) {
    return new Promise((resolve, reject) => {

        let base = getBaseArg();
        if (!isApp()) {

            if (flag) {
                resolve(base);
            } else {
                reject(401);
            }
            return
        }
        //这里的问题，在不登录没有登录

        window.hxsappPlusGetUserAgent = (data) => {
            // 检查响应是否存在
            const { func1, func2 } = funcs.shift();
            if (data) {
                if (isAndroid()) {
                    const query = new URLSearchParams(data);
                    if (query.get('sess_token')) {
                        base = {
                            sess_token: query.get('sess_token'),
                            utime: query.get('utime'),
                            sign: decodeURIComponent(query.get('sign'))
                        };

                        func1(base)
                    } else {
                        if (flag) {
                            func1(base);
                        } else {
                            window.location.href = 'https://hxsapp_showloginpage';
                            func2(401);
                        }
                    }

                } else {
                    const query = data;
                    if (query['sess_token']) {
                        base = {
                            sess_token: query['sess_token'],
                            utime: query['utime'],
                            sign: decodeURIComponent(query['sign'])
                        };
                        func1(base);
                    } else {

                        if (flag) {
                            func1(base);
                        } else {
                            window.location.href = 'https://hxsapp_showloginpage';
                            func2(401);
                        }
                    }
                }
            } else {

                if (flag) {
                    func1(base);
                } else {
                    window.location.href = 'https://hxsapp_showloginpage';
                    func2(401);
                }
            }
        }


        funcs.push({
            func1: resolve,
            func2: reject
        })


        if (isAndroid()) {
            window.TokenJsInterface && window.TokenJsInterface.getData('');
        } else {
            window.webkit.messageHandlers.TokenJsInterface && window.webkit.messageHandlers.TokenJsInterface.postMessage('');

        }

    }).catch(error => {
        console.log("异常抛出3")
    })
}



function sendRequest(type, url, params, flag, headers, warning, responseType = '', all = false) {
    return new Promise((resolve, reject) => {

        getUserInfo(flag).then(info => {
            console.log("url=", url)
            if (info === 401) {
                return reject(info);
            }
            let paramsList = {
                ...info,
                ...params,
                _: Date.now()
            }
            return axios.post(url, paramsList, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': Authorization(),
                    ...headers

                },
                transformRequest: [() => {
                    return Encrypt(buildParams(paramsList))
                }]
            })
        }).then(res => {

            let {
                code,
                msg
            } = res.data;
            console.log("🚀 ~ getUserInfo ~ code:", code)

            if (all) return resolve(res.data);
            if (String(code) === '401') {
                if (isApp() && !flag) window.location.href = 'https://hxsapp_showloginpage';
                return reject(401);
            }
            if (String(code) !== '200') {
                if (warning) {
                    Toast(msg || 'API 接口出错!');
                }
                reject(res.data);
            } else {
                let iv = res.data.data.substring(0, 16)
                let str = res.data.data.substring(16)
                let listData = JSON.parse(Decrypt(str, iv))
                if (String(listData.code) === '401') {
                    return reject(401);
                }
                if (String(listData.code) !== '200') {
                    if (warning) {
                        Toast(listData.msg || 'API 接口出错!');
                    }
                    reject(listData);
                    return
                }
                resolve(listData.data);
            }
        }).catch(e => {

            if (warning) {
                if (e !== 401) {
                    Toast(e.message || '数据请求失败!');
                }
            }

            reject(e);
        })


    })
}



export function postAes(url, data = {}, flag = false, headers = {}, warning = false) {
    return sendRequest('POST', url, data, flag, headers, warning); //新的请求，走js交互
}